# -*- coding: utf-8 -*-

import sys
import os
import requests
import json
import time
import re
import traceback,threading

print('>>>正在初始化...')

HTTP_SB_URL = 'http://ydhzcms.bimsheng.com/daping/rest/people/'
proDir = os.path.split(os.path.realpath(__file__))[0]
print('proDir---',proDir)
proDir = proDir.replace('\dist','')
import time
from selenium import webdriver
def loginurl(account='',password='',miniters=300):
    cookie = None
    #创建一个浏览器对象
    # browser = webdriver.Firefox(executable_path='C:\\geckodriver')

    profile=webdriver.FirefoxProfile()

    profile.accept_untrusted_certs=True

    geckodriverPath = os.path.join(proDir, "geckodriver")
    browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) 
    try:
        # browser.get('https://m.bet13651.tv')
        browser.get('https://m.bet13651.tv/#module/member/action/login')

        time.sleep(2)

        maindiv = browser.find_elements_by_class_name('form-control')

        # print(maindiv)
        # maindiv[0].send_keys(account)

        # pw_input = browser.find_element_by_id('mdl-1_password')
  
        #定位到账号的输入框
        # id_input = browser.find_element_by_xpath('//input[@id="mdl-1_username"]')
        id_input = maindiv[0]
        time.sleep(2)
        id_input.send_keys(account)
        #定位到密码输入框，输入密码
        # pw_input = browser.find_element_by_xpath('//input[@id="mdl-1_password"]')
        pw_input = maindiv[1]
        pw_input.send_keys(password)
        time.sleep(1)
        # #点击登录按钮
        login_btn = maindiv[2]
        # browser.find_element_by_xpath('//button[@class="btn btn-primary form-control submit-btn"]').click()
        login_btn.click()
        time.sleep(3)

        confirm_btn = browser.find_elements_by_class_name('confirm-btn')
        
        if len(confirm_btn)>0:
            cookie={}
            dictCookies=browser.get_cookies()
            jsonCookies = json.dumps(dictCookies)

            # 登录完成后，将cookie保存到本地文件
            with open('cookies.json', 'w') as f:
                f.write(jsonCookies)
            # for i in browser.get_cookies():
            #     cookie[i["name"]] = i["value"]
            # with open("cookies.txt","w") as f:
            #     f.write(json.dumps(cookie))
        confirm_btn[0].click()

        time.sleep(2)
        confirm_btn = browser.find_elements_by_class_name('confirm-btn')
        print(confirm_btn)
        if len(confirm_btn)>0:
            confirm_btn[0].click()

        confirm_btn = browser.find_elements_by_class_name('confirm-btn')
        if len(confirm_btn)>0:
            confirm_btn[0].click()

        confirm_btn = browser.find_elements_by_class_name('confirm-btn')
        if len(confirm_btn)>0:
            confirm_btn[0].click()

        confirm_btn = browser.find_elements_by_class_name('confirm-btn')
        if len(confirm_btn)>0:
            confirm_btn[0].click()

        caipiao(dictCookies,browser)
        # tabs = browser.find_element_by_xpath('//ul[@class="tabs"]')
        # time.sleep(2)
        # # print('tabs----',tabs)
        # caipiao_tab = tabs.find_element_by_xpath('//span[text()="彩票"]')
        # print('caipiao_tab----',caipiao_tab)
        # caipiao_tab.click()
        # litabs = tabs.find_elements_by_xpath('//li[@caipiao="caipiao"]')
        # print('litabs----',litabs)

        # caipiao(dictCookies,browser)
        # try:
        #     tiaoguo = browser.find_element_by_xpath('//a[@id="login-form-cancel"]')
        #     if tiaoguo:
        #         tiaoguo.click()
        # except:
        #     print('无需跳过')
        
        # # #获取登录的cookie
        # cookie = browser.get_cookies()
        # cookie = cookie[0]
        # cookie = cookie['name']+'='+cookie['value']
        # time.sleep(3)
        # browser.switch_to.window(browser.window_handles[-1])
        # time.sleep(3)
        # szkb = browser.find_element_by_xpath('//div[text()="企业看板"]')
        # # action_chains.double_click(szkb).perform()
        # szkb.click()
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8/EPM/MC/EpmMetopeOptions/EpmMetopeShow?AppTitle=%E4%BC%81%E4%B8%9A%E7%9C%8B%E6%9D%BF")]')
        # browser.switch_to.frame(iframe)
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8//EPM/MC/EpmStatichtml/StatichtmlView?id=139")]')
        # browser.switch_to.frame(iframe)
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"../page3/projectMap.html?t=")]')
        # browser.switch_to.frame(iframe)
        
        # time.sleep(3)
        # shtsgxm_c = browser.find_element_by_xpath('//div[text()="中国共产党第一次全国代表大会纪念馆"]')
        # shtsgxm_c.click()

        # browser.switch_to_default_content()#切出当前iframe
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8/EPM/MC/EpmMetopeOptions/EpmMetopeShow?mtype=1&projId=348200211000008&AppTitle=%E9%A1%B9%E7%9B%AE%E6%8C%87%E6%8C%A5%E4%B8%AD%E5%BF%83")]')
        # browser.switch_to.frame(iframe)

        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8//EPM/MC/EpmStatichtml/StatichtmlView?id=140")]')
        # browser.switch_to.frame(iframe)
        
        # ####获取人员信息
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"../page3/workerRegister.html?t=")]')
        # browser.switch_to.frame(iframe)
        # time.sleep(3)
        # #获取该节点下的所有子节点
        # # jinrijinchu = browser.find_element_by_xpath('//div[contains(text(),"今日进出人次")]').get_attribute('innerHTML')#可行方案
        # jinrijinchu = browser.find_elements_by_class_name('attendance-item-left-item')
        # today_peoples = '0'
        
        
    except:
        traceback.print_exc()
        print('异常处理')
    
    # if browser:
    #     browser.close()
    # return cookie

def caipiao(dictCookies,browser):
    cookie = None
    print('访问彩票界面----',dictCookies,'---',type(dictCookies))
    #创建一个浏览器对象
    # browser = webdriver.Firefox(executable_path='C:\\geckodriver')

    # profile=webdriver.FirefoxProfile()

    # profile.accept_untrusted_certs=True

    # geckodriverPath = os.path.join(proDir, "geckodriver")
    # browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) 
    try:
        
        browser.get('https://m.tgtiantiancai.com/#module/lotteryTtsfc/type/zhenghe')
        browser.delete_all_cookies()
        for cookie in dictCookies:
            # print('listCookies---',cookie,type(cookie))
            browser.add_cookie({
                'domain': cookie['domain'],  # 此处xxx.com前，需要带点
                'name': cookie['name'],
                'value': cookie['value'],
                'path': cookie['path'],
                'secure':cookie['secure'],
                'httpOnly': cookie['httpOnly']
            })
        browser.get('https://m.tgtiantiancai.com/#module/lotteryTtsfc/type/zhenghe')

        time.sleep(2)
        
    except:
        traceback.print_exc()
        print('异常处理')
def usecookie(account='',password='',miniters=300):
    cookie = None
    #创建一个浏览器对象
    # browser = webdriver.Firefox(executable_path='C:\\geckodriver')

    profile=webdriver.FirefoxProfile()

    profile.accept_untrusted_certs=True

    geckodriverPath = os.path.join(proDir, "geckodriver")
    browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) 
    try:
        
        with open('cookies.json', 'r', encoding='utf-8') as f:
            listCookies = json.loads(f.read())
        
        # print('listCookies---',listCookies)
        
        browser.get('https://m.bet13651.tv')
        browser.delete_all_cookies()
        time.sleep(2)
        for cookie in listCookies:
            # print('listCookies---',cookie,type(cookie))
            browser.add_cookie({
                'domain': cookie['domain'],  # 此处xxx.com前，需要带点
                'name': cookie['name'],
                'value': cookie['value'],
                'path': cookie['path'],
                'secure':cookie['secure'],
                'httpOnly': cookie['httpOnly']
            })
        browser.get('https://m.bet13651.tv')

        time.sleep(2)
        confirm_btn = browser.find_elements_by_class_name('confirm-btn')
        print(confirm_btn)
        confirm_btn[2].click()
        confirm_btn[1].click()
        confirm_btn[0].click()
    except:
        traceback.print_exc()
        print('异常处理')
    


class MainThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        config = configparser.ConfigParser()
        
        configPath = os.path.join(proDir, "config.ini")
        config.read(configPath)
        username = config.get('config','username')
        password = config.get('config','password')
        miniters = int(config.get('config','miniters'))
        while True:
            try:
                loginurl(username,password,miniters)
            except Exception as e:
                print('登录主线程报错，继续执行。。。。')
                traceback.print_exc()
            
            time.sleep(miniters)
    
import configparser
if __name__ == '__main__':
    print(">>>>>>>>  login")
    
    # MainThread().start()
    # print('执行成功')
    # time.sleep(2)

    config = configparser.ConfigParser()  
    configPath = os.path.join(proDir, "config.ini")
    config.read(configPath)
    username = config.get('config','username')
    password = config.get('config','password')
    miniters = int(config.get('config','miniters'))
    try:
        loginurl(username,password,miniters)
        # usecookie(username,password,miniters)
    except Exception as e:
        print('登录主线程报错，继续执行。。。。')
        traceback.print_exc()

